package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"news/models"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type NewsController struct {
	beego.Controller
}

func (c *NewsController) Add() {
	title := c.GetString("title")
	author := c.GetString("author")
	img := c.GetString("img")
	cateId, _ := c.GetInt("cateId")
	status := c.GetString("status")

	news := models.News{
		Title:  title,
		Author: author,
		Img:    img,
		CateId: uint(cateId),
		Status: status,
	}

	err := models.DB.Create(&news).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *NewsController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件获取失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	defer file.Close()
	path := "static/img/" + header.Filename

	ext := map[string]bool{
		".png":  true,
		".jpeg": true,
		".jpg":  true,
	}

	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if !ext[suffix] {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "格式不正确",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if header.Size > 2*1024*1024 {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件过大",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		Img := "http://127.0.0.1:8080/" + path
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "文件上传成功",
			Data: Img,
		}
		c.ServeJSON()
	}
}

func (c *NewsController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	title := c.GetString("title")

	jsonData := make(map[string]interface{})
	query := models.DB.Model(&models.News{})

	key := "list:" + strconv.Itoa(page) + title
	val, err := models.Rdb.Get(key).Result()

	if title != "" {
		query.Where("title like ? ", "%"+title+"%")
	}

	if err != nil {
		var count int64
		err = query.Count(&count).Error
		var news []models.News
		offset := (page - 1) * size
		err = models.DB.Preload("NewType").Offset(offset).Limit(size).Find(&news).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {

			jsonData["news"] = news
			jsonData["count"] = count
			jsonData["page"] = page

			res, _ := json.Marshal(&jsonData)
			value := string(res)
			models.Rdb.Set(key, value, time.Second*30)

			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: jsonData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &jsonData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: jsonData,
		}
		c.ServeJSON()
	}
}

func (c *NewsController) Info() {
	id, _ := c.GetInt("id")
	var newes models.News

	key := "info:" + strconv.Itoa(id)
	keys := "rank"
	val, err := models.Rdb.Get(key).Result()

	if err != nil {
		err = models.DB.Preload("NewType").Where("id=?", id).First(&newes).Error
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {

			res, _ := json.Marshal(&newes)
			value := string(res)
			models.Rdb.Set(key, value, time.Second*60)

			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "查询成功-mysql",
				Data: newes,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), &newes)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: newes,
		}
		c.ServeJSON()
	}
	models.Rdb.ZIncrBy(keys, 1, newes.Title)
}

func (c *NewsController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.News{}, id).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *NewsController) Lop() {
	var lop []models.NewType
	err := models.DB.Find(&lop).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "没有该分类",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: lop,
		}
		c.ServeJSON()
	}
}

func (c *NewsController) Comment() {
	author := c.GetString("author")
	newsId, _ := c.GetInt("newsId")
	userId, _ := c.GetInt("userId")

	commit := models.Comment{
		Author: author,
		NewsId: uint(newsId),
		UserId: uint(userId),
	}
	err := models.DB.Create(&commit).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "评论失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "评论成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *NewsController) Collection() {

	newId, _ := c.GetInt("newId")
	userId, _ := c.GetInt("userId")
	commit := models.Collection{

		NewId:  uint(newId),
		UserId: uint(userId),
	}
	err := models.DB.Create(&commit).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "不登录收藏失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "收藏成功",
			Data: nil,
		}
		c.ServeJSON()

	}
}

func (c *NewsController) CollList() {
	var collectlist []models.Collection
	err := models.DB.Preload("News").Preload("User").Find(&collectlist).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "收藏查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "收藏查询成功",
			Data: collectlist,
		}
		c.ServeJSON()

	}
}

func (c *NewsController) Rank() {
	key := "rank"
	slice, err := models.Rdb.ZRevRangeWithScores(key, 0, -1).Result()
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: slice,
		}
		c.ServeJSON()

	}
}
